import argparse
from functools import lru_cache
import os
import sys
from pathlib import Path

from dotenv import load_dotenv
from pydantic.v1 import BaseSettings

# pip install python-dotenv


class AppSettings(BaseSettings):
    """
    应用配置
    """

    app_env: str = "dev"
    app_name: str = "crawler_server"
    app_debug: bool = True
    app_docs_url: str | None = "/docs"
    app_redoc_url: str | None = "/redoc"
    app_root_path: str = "/api/v1"
    app_host: str = "0.0.0.0"
    app_port: int = 5050
    app_version: str = "es"
    app_reload: bool = True
    app_workers: int = 1


class MysqlSettings(BaseSettings):
    """
    mysql配置
    """

    # db_host: str = "127.0.0.1"
    db_host: str = "rm-uf6vr38g39njv6exb4o.rwlb.rds.aliyuncs.com"
    db_port: int = 3306
    # db_username: str = "root"
    db_username: str = "crm_test"
    # db_password: str = "sql123"
    db_password: str = "PxBJe3F7jpb2diKx"
    # db_database: str = "test"
    db_database: str = "crm_test"
    db_echo: bool = True
    db_max_overflow: int = 50
    db_pool_size: int = 100
    db_pool_recycle: int = 3600
    db_pool_timeout: int = 120

class RedisSettings(BaseSettings):
    """
    Redis配置
    """

    redis_host: str = "127.0.0.1"
    redis_port: int = 6379
    redis_username: str = ""
    redis_password: str = "123456"
    redis_database: int = 0
    redis_max_connections: int = 50


class GetConfig:
    """
    获取配置
    """

    def __init__(self):
        self.choose_env()

    @lru_cache()
    def get_app_config(self):
        """
        获取应用配置
        """
        # 实例化应用配置模型
        return AppSettings()

    @lru_cache()
    def get_mysql_config(self):
        """
        获取mysql配置
        """
        # 实例化mysql配置模型
        return MysqlSettings()

    @lru_cache()
    def get_redis_config(self):
        """
        获取Redis配置
        """
        # 实例化Redis配置模型
        return RedisSettings()

    @staticmethod
    def choose_env():
        # 读取运行环境
        run_env = os.environ.get("APP_ENV")
        # 运行环境未指定时默认加载.env
        print(f"当前运行环境: {run_env}")
        if not run_env:
            run_env = "local"
        env_file = ".env"
        if run_env != "local":
            env_file = f".env.{run_env}"
        # 加载配置
        dotenv_path = Path('.') / env_file
        print(f"加载配置文件: {dotenv_path}")
        result = load_dotenv(dotenv_path=dotenv_path)

os.environ['APP_ENV'] = 'dev'
# 实例化获取配置类
get_config = GetConfig()
# 应用配置
AppConfig = get_config.get_app_config()
# mysql配置
MysqlConfig = get_config.get_mysql_config()
# Redis配置
RedisConfig = get_config.get_redis_config()